import { createSSEData } from './common';

interface IResponseData {
  isStream?: boolean;
  sessionId: string;
  getAgentStream?: () => Promise<any>;
  getAgentInvoke?: () => Promise<any>;
}

export const useResponseData = async (params: IResponseData) => {
  //  非流式
  if (!params.isStream) {
    const response = await params.getAgentInvoke?.();
    return response.messages.at(-1).content;
  }

  const stream = new ReadableStream({
    async start(controller) {
      try {
        let fullResponse = '';
        let stepCount = 0;

        // 使用 stream 方法进行流式输出
        const agentStream = await params.getAgentStream?.();

        for await (const chunk of agentStream) {
          stepCount++;

          // 处理不同类型的流式数据
          if (Array.isArray(chunk) && chunk.length === 2) {
            const [messageChunk, metadata] = chunk;

            if (messageChunk?.content && metadata?.langgraph_node === 'agent') {
              // 处理不同类型的消息内容
              let contentText = '';
              if (typeof messageChunk.content === 'string') {
                contentText = messageChunk.content;
              } else if (Array.isArray(messageChunk.content)) {
                // 处理复杂内容数组
                contentText = messageChunk.content
                  .map((item: any) => {
                    if (typeof item === 'string') {
                      return item;
                    } else if (
                      item &&
                      typeof item === 'object' &&
                      'text' in item
                    ) {
                      return item.text;
                    }
                    return '';
                  })
                  .join('');
              }

              if (contentText) {
                // 直接发送内容，不累积
                const streamData = {
                  type: 'chunk',
                  text: contentText,
                  step: stepCount,
                  sessionId: params.sessionId,
                };

                controller.enqueue(createSSEData(streamData));
                fullResponse += contentText;
              }
            }
          } else if (chunk && typeof chunk === 'object' && 'content' in chunk) {
            // 直接的内容流
            let contentText = '';
            if (typeof chunk.content === 'string') {
              contentText = chunk.content;
            } else if (Array.isArray(chunk.content)) {
              contentText = chunk.content
                .map((item: any) => {
                  if (typeof item === 'string') {
                    return item;
                  } else if (
                    item &&
                    typeof item === 'object' &&
                    'text' in item
                  ) {
                    return item.text;
                  }
                  return '';
                })
                .join('');
            }

            if (contentText) {
              // 直接发送内容，不累积
              const streamData = {
                type: 'chunk',
                text: contentText,
                step: stepCount,
                sessionId: params.sessionId,
              };

              controller.enqueue(createSSEData(streamData));
              fullResponse += contentText;
            }
          }
        }

        // 发送完成信号
        const finalData = {
          type: 'end',
          text: fullResponse,
          metadata: {
            source: 'gis_langgraph_stream',
            sessionId: params.sessionId,
            totalSteps: stepCount,
          },
        };

        controller.enqueue(createSSEData(finalData));
        controller.close();
      } catch (error) {
        console.error('流式处理错误:', error);

        // 获取错误信息
        let errorMessage = '流式处理失败';

        if (error instanceof Error) {
          errorMessage = error.message;
        }

        const errorData = {
          type: 'error',
          error: errorMessage,
          sessionId: params.sessionId,
        };
        controller.enqueue(createSSEData(errorData));
        controller.close();
      }
    },
  });

  return stream;
};

// 简单版
export const useResponseDataSimple = async (params: IResponseData) => {
  //  非流式
  if (!params.isStream) {
    const response = await params.getAgentInvoke?.();
    return response.messages.at(-1).content;
  }

  const stream = new ReadableStream({
    async start(controller) {
      try {
        let fullResponse = '';
        let stepCount = 0;

        // 使用 stream 方法进行流式输出
        const agentStream = await params.getAgentStream?.();

        for await (const chunk of agentStream) {
          stepCount++;
          const [messageChunk] = chunk;
          let contentText = '';
          contentText = messageChunk.content;
          if (contentText) {
            // 直接发送内容，不累积
            const streamData = {
              type: 'token',
              text: contentText,
              step: stepCount,
              sessionId: params.sessionId,
            };

            controller.enqueue(createSSEData(streamData));
            fullResponse += contentText;
          }
        }

        // 发送完成信号
        const finalData = {
          type: 'done',
          text: fullResponse,
          metadata: {
            source: 'gis_langgraph_stream',
            sessionId: params.sessionId,
            totalSteps: stepCount,
          },
        };

        controller.enqueue(createSSEData(finalData));
        controller.close();
      } catch (error) {
        console.error('流式处理错误:', error);
        // 获取错误信息
        let errorMessage = '流式处理失败';

        if (error instanceof Error) {
          errorMessage = error.message;
        }

        const errorData = {
          type: 'error',
          error: errorMessage,
          sessionId: params.sessionId,
        };
        controller.enqueue(createSSEData(errorData));
        controller.close();
      }
    },
  });

  return stream;
};
